package server

import (
	"context"
	"encoding/base64"
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	util2 "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/sdk/tx"
	"longmen/server/pkg/db/mysql/db_sports"
	cache2 "longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
)

func (s *Server) OfficialLiveRoom(ctx context.Context, req *pb.OfficialLiveReq) (*pb.OfficialLiveResp, error) {
	var pullUrl string
	official := &pb.OfficialLiveResp{}
	var err error
	var matchData *api_models.EsMatchTempSchedule
	if global2.Lang.GetLang() != util2.LangChinese {
		matchData, err = db_sports.GetMysqlIdByInfo(int(req.GetMatchId()), int(req.SportId))
	} else {
		matchData, err = db_sports.GetEsIdByInfo(int(req.GetMatchId()), int(req.SportId))
	}

	if err != nil {
		return nil, err
	}
	global2.Log.Debugf("官方直播间req id:%v,matchData.MatchId:%v,err:%v", req.GetMatchId(), matchData.MatchId, err)
	if matchData.MatchId > 0 {
		official = &pb.OfficialLiveResp{
			MatchId: int32(matchData.MatchId),
			Title:   matchData.Comp,
			PullUrl: pullUrl,
			RoomId:  int32(matchData.MatchId),
			SportId: int32(matchData.SportId),
		}
		setAnimationUrl(official, req.GetPlatform())
		//if matchData.MatchStatus == db_sports.MatchStaring {
		stream := db_sports.GetLiveVideoStream(global2.Sport(), official.GetMatchId())
		//global2.Log.Debugf("官方直播间stream:%+v", stream)
		if stream != "" {
			official.VideoUrl = tx.CreateSatelliteLiveUrl(tx.HostFLV, stream, 0)[0]
			official.VideoUrl2 = tx.CreateSatelliteLiveUrl(tx.HostFLV, stream+global2.Config.GetString("livespeed1"), 0)[0]
			official.HlsVideoUrl = tx.CreateSatelliteLiveUrl(tx.HostHLS, stream, 0)[0]
			official.HlsVideoUrl2 = tx.CreateSatelliteLiveUrl(tx.HostHLS, stream+global2.Config.GetString("livespeed1"), 0)[0]
			official.Stream = stream
			cache2.SetVideoViewerNum(matchData.MatchId, 1)
		}
		//}
	}
	return official, nil

}

func setAnimationUrl(official *pb.OfficialLiveResp, platform int32) {
	if official.SportId > 0 {
		if official.SportId == util2.FOOT_BALL_SPORT_ID {
			official.PullUrl = fmt.Sprintf(util2.FootBallAnimationUrl, official.GetMatchId())
		} else if official.SportId == util2.CRICKET_BALL_SPORT_ID {
			official.PullUrl = fmt.Sprintf(util2.CricketAnimationUrl, official.GetMatchId())
			if platform == util2.TERMINAL_ANDROID {
				configPub := cache2.GetConfigPub()
				encodedString := base64.StdEncoding.EncodeToString([]byte(official.PullUrl))
				official.PullUrl = fmt.Sprintf("%splay-url-wrap?url=%s", configPub.H5Domain, encodedString)
			}
		} else {
			if platform == 0 {
				official.PullUrl = fmt.Sprintf(util2.BasketBallAnimationUrl, official.GetMatchId())
			} else {
				official.PullUrl = fmt.Sprintf(util2.BasketBallAnimationAppUrl, official.GetMatchId())
			}
		}
	}
}
